package com.java.shop.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.java.common.constant.ProductConstant;
import com.java.common.exception.MyException;
import com.java.common.utils.PageUtils;
import com.java.common.utils.Query;
import com.java.shop.product.dao.AttrDao;
import com.java.shop.product.entity.AttrAttrgroupRelationEntity;
import com.java.shop.product.entity.AttrEntity;
import com.java.shop.product.entity.AttrGroupEntity;
import com.java.shop.product.exception.ProductExceptionEnum;
import com.java.shop.product.service.AttrAttrgroupRelationService;
import com.java.shop.product.service.AttrGroupService;
import com.java.shop.product.service.AttrService;
import com.java.shop.product.service.CategoryService;
import com.java.shop.product.vo.AttrRespVo;
import com.java.shop.product.vo.AttrVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Slf4j
@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    AttrAttrgroupRelationService attrAttrgroupRelationService;

    @Autowired
    CategoryService categoryService;

    @Autowired
    AttrGroupService attrGroupService;


    @Override
    public PageUtils queryPage(Map<String, Object> params, Long id, String type) {
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        //根据url路径判断是查询销售属性还是基本属性
        Integer attrType = "base".equalsIgnoreCase(type) ? ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() : ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode();
        wrapper.eq("attr_type",attrType);
        if(id != 0) wrapper.eq("catelog_id",id);
        //若有其他搜索条件就加上
        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            wrapper.and(item->{
                item.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );
        //查询到的当前Attr表中的数据
        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> records = page.getRecords();
        //查询返回AttrRespVo的集合
        List<AttrRespVo> respVos = records.stream().map(item->{
            //将AttrEntity中的数据线拷贝到AttrRespVo
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(item,attrRespVo);

            //查询分类名称
            Long catelogId = attrRespVo.getCatelogId();
            if(catelogId != null){
                String name = categoryService.getById(catelogId).getName();
                attrRespVo.setCatelogName(name);
            }

            //销售属性无需分组
            if(attrType == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
                //查询分组名称，根据属性ID查关联表，在根据关联表中查到的属性分组ID查询
                Long attrId = attrRespVo.getAttrId();
                QueryWrapper<AttrAttrgroupRelationEntity> wr = new QueryWrapper<>();
                wr.eq("attr_id",attrId);
                AttrAttrgroupRelationEntity attrgroupRe = attrAttrgroupRelationService.getOne(wr);
                if(attrgroupRe != null){
                    attrRespVo.setAttrGroupId(attrgroupRe.getAttrGroupId());
                    AttrGroupEntity attrGroupEntity = attrGroupService.getById(attrgroupRe.getAttrGroupId());
                    if(attrGroupEntity != null) attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }


            return attrRespVo;
        }).collect(Collectors.toList());
        pageUtils.setList(respVos);
        return pageUtils;
    }

    @Transactional
    @Override
    public void saveAndOther(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);
        this.save(attrEntity);
        //为基本属性时才保存属性分组
        if(attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
            //保存属性的同时保存属性分组与属性的关联表
            AttrAttrgroupRelationEntity entity = new AttrAttrgroupRelationEntity();
            entity.setAttrId(attrEntity.getAttrId());
            entity.setAttrGroupId(attr.getAttrGroupId());
            attrAttrgroupRelationService.save(entity);
        }
    }

    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        AttrEntity attrEntity = this.getById(attrId);
        if(attrEntity == null) throw new MyException(ProductExceptionEnum.ATTR_NOTFOUND_EXCEPTION.getCode(),ProductExceptionEnum.ATTR_NOTFOUND_EXCEPTION.getMsg());
        AttrRespVo attrRespVo = new AttrRespVo();
        BeanUtils.copyProperties(attrEntity,attrRespVo);
        Long catelogId = attrRespVo.getCatelogId();
        if(catelogId == null) throw new MyException(ProductExceptionEnum.CATELOG_NOTFOUND_EXCEPTION.getCode(),ProductExceptionEnum.CATELOG_NOTFOUND_EXCEPTION.getMsg());

        //查询分类信息
        List<Long> parentIds = categoryService.getParentIds(catelogId);
        attrRespVo.setCatelogPath(parentIds);

        if(attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
            //查询分组信息
            QueryWrapper<AttrAttrgroupRelationEntity> wr = new QueryWrapper<>();
            wr.eq("attr_id",attrId);
            AttrAttrgroupRelationEntity attrgroupRe = attrAttrgroupRelationService.getOne(wr);
            if(attrgroupRe != null){
                attrRespVo.setAttrGroupId(attrgroupRe.getAttrGroupId());
                AttrGroupEntity attrGroupEntity = attrGroupService.getById(attrgroupRe.getAttrGroupId());
                if(attrGroupEntity != null) attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
            }
        }

        return attrRespVo;
    }

    @Transactional
    @Override
    public void updateDetails(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);
        this.update(attrEntity,new QueryWrapper<AttrEntity>().eq("attr_id",attrEntity.getAttrId()));
        if(attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
            QueryWrapper<AttrAttrgroupRelationEntity> wr = new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId());
            int count = attrAttrgroupRelationService.count(wr);
            AttrAttrgroupRelationEntity attrRelation = new AttrAttrgroupRelationEntity();
            if(count > 0){
                //更新关联表
                if(attr.getAttrGroupId() == null){
                    attrRelation.setAttrGroupId(0L);
                }else{
                    attrRelation.setAttrGroupId(attr.getAttrGroupId());
                }
                attrAttrgroupRelationService.update(attrRelation,wr);
            }else{
                //添加到关联表
                attrRelation.setAttrGroupId(attr.getAttrGroupId());
                attrRelation.setAttrId(attrEntity.getAttrId());
                attrAttrgroupRelationService.save(attrRelation);
            }
        }
    }

    @Override
    public PageUtils noAttrRelation(Map<String, Object> params, Long groupId) {
        //1、当前分组只能关联自己所属分类的属性
        AttrGroupEntity attrGroupEntity = attrGroupService.getById(groupId);
        if(attrGroupEntity == null) return null;
        Long catelogId = attrGroupEntity.getCatelogId();
        if(catelogId == null) return null;
        List<AttrGroupEntity> attrGroupList = attrGroupService.list(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
        if(attrGroupList.size() == 0) return null;
        List<Long> attrGroupIds = attrGroupList.stream().map(item->item.getAttrGroupId()).collect(Collectors.toList());

        //2、当前分组只能关联其他分组没有引用的属性
        //查询出所有符合条件分组下的attrid,即查询到属性有关联的分组
        List<AttrAttrgroupRelationEntity> relationList = attrAttrgroupRelationService.list(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", attrGroupIds));
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        if(relationList.size() != 0){
            List<Long> attrIds = relationList.stream().map(item->item.getAttrId()).collect(Collectors.toList());
            wrapper.notIn("attr_id",attrIds);
        }

        //查询本分类下没有关联分组的属性信息
        wrapper.eq("catelog_id",catelogId);
        wrapper.eq("attr_type",ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params),wrapper);
        return new PageUtils(page);
    }
}